﻿#if UNITY_EDITOR

using System;
using System.Collections.Generic;
using UnityEngine;

namespace AI.Graph.Editor {


    public class EventSystem {

        private static EventSystem m_instance;

        public static EventSystem current {
            get { return m_instance; }
        }


        private List<GraphEvent> m_events = new List<GraphEvent> ();
        private AIGraph m_graph;


        public AIGraph graph {
            get { return m_graph; }
        }


        public EventSystem (AIGraph graph) {
            m_graph = graph;

            m_instance = this;

            LoadEvents ();
        }


        void LoadEvents () {
            foreach (Type t in ReflectionUtility.LoadClassTypes<GraphEvent> ()) {
                GraphEvent graphEvent = ScriptableObject.CreateInstance (t) as GraphEvent;

                if (graphEvent == null) {
                    Debug.Log ("GraphEvent creation failed. [" + t.Name + "]");
                    continue;
                }

                GraphEventOrder graphOrder = graphEvent.GetType ().GetAttribute<GraphEventOrder> ();
                if (graphOrder != null) {
                    graphEvent.order = graphOrder.order;
                }

                for (int i = 0; i < m_events.Count; i++) {
                    if (graphEvent.order > m_events[i].order) {
                        m_events.Insert (i, graphEvent);
                        break;
                    }
                }

                m_events.Add (graphEvent);
            }

            for (int i = 0; i < m_events.Count; i++) {
                m_events[i].OnInitialize ();
            }
        }


        public void Process () {
            for (int i = 0; i < m_events.Count; i++) {
                m_events[i].OnProcess (Event.current);
            }
        }

    }


}
#endif